package com.acc.sys.controller;

import com.acc.sys.framework.AccParser;
import com.acc.sys.service.AdminAuthService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;

@RestController
@RequestMapping("/sys")
@AllArgsConstructor
public class SysController {

    private AdminAuthService adminAuthService;

    @PostMapping("/login")
    public String login(@RequestBody String request) {
        JSONObject requestObj = JSON.parseObject(request);
        if (requestObj == null) {
            return JSON.toJSONString(AccParser.newErrorResult(new UnsupportedEncodingException("JSON格式不合法！"), true));
        }
        JSONObject loginInfo = adminAuthService.login(requestObj.getString("username"), requestObj.getString("password"));
        return JSONObject.toJSONString(AccParser.extendSuccessResult(loginInfo));
    }

    /**
     * @return 菜单列表
     */
    @PostMapping("routes")
    public String routes() {
        JSONObject object = new JSONObject();
        object.put("data", adminAuthService.routes());
        return JSONObject.toJSONString(AccParser.extendSuccessResult(object));
    }

    /**
     * 删除菜单
     *
     * @param request {"id":"菜单ID"}
     * @return 删除菜单
     */
    @PostMapping("deleteMenu")
    public String deleteMenu(@RequestBody String request) {
        JSONObject params = JSON.parseObject(request);
        if (params == null) {
            return JSON.toJSONString(AccParser.newErrorResult(new UnsupportedEncodingException("JSON格式不合法！"), true));
        }
        JSONObject retData = adminAuthService.deleteMenu(params.getString("id"));
        return JSONObject.toJSONString(retData);
    }

    /**
     * 删除部门
     *
     * @param request {"id":"菜单ID"}
     * @return 删除菜单
     */
    @PostMapping("deleteDept")
    public String deleteDept(@RequestBody String request) {
        JSONObject params = JSON.parseObject(request);
        if (params == null) {
            return JSON.toJSONString(AccParser.newErrorResult(new UnsupportedEncodingException("JSON格式不合法！"), true));
        }
        JSONObject retData = adminAuthService.deleteDept(params.getString("id"));
        return JSONObject.toJSONString(retData);
    }

    /**
     * 保存管理员
     */
    @PostMapping("saveAdmin")
    public String saveAdmin(@RequestBody String request) {
        JSONObject params = JSON.parseObject(request);
        if (params == null) {
            return JSON.toJSONString(AccParser.newErrorResult(new UnsupportedEncodingException("JSON格式不合法！"), true));
        }
        return JSONObject.toJSONString(adminAuthService.saveAdmin(params));
    }
}
